from .models import College, Major, StudentClass, Student, School
from django.db.models.query import EmptyQuerySet
from hg_survey.logging import evt_logger
from django.contrib.auth.hashers import make_password
import pandas as pd

def create_school(items):
    pass

def create_college(items):
    col = College.objects.all()


def create_major(items):
    pass


def create_class(items):
    pass


def create_student(items):
    pass

def clean_all():
    student = Student.objects.all()
    student.delete()
    student_class = StudentClass.objects.all()
    student_class.delete()
    major_set = Major.objects.all()
    major_set.delete()
    college_set = College.objects.all()
    college_set.delete()
    school = School.objects.all()
    school.delete()

def batch_create_college(filename):
    cols = ['学校', '学院', '代码', '简称']
    rdata = pd.read_csv(filename)
    rdata.fillna('', inplace=True)

    count = 0
    for _, series in rdata.iterrows():
        sc = series['学校']
        college = series['学院']
        code = series['代码']
        short_name = series['简称']

        info = f'{college}-{code}-{short_name}'

        try:
            school = School.objects.get(name=sc)
        except School.DoesNotExist:
            school = School(name=sc)
            school.save()
        
        item = College(school=school,
                       name=college,
                       code=code,
                       short_name=short_name,
                       active=True)
        try:
            item.save()
        except Exception as e:
            evt_logger.error(f'create_college: {info} {e}')
            continue
        else:
            evt_logger.info(f'insert_college ({count}): {info}')

        count += 1

    print(f'Total insert {count} colleges.')
        
# $todo:
# force: 学院缺失的情况下会增加学院
def batch_create_major(filename, school, force=False):
    college_set = College.objects.filter(school__name=school)
    
    if college_set is EmptyQuerySet:
        message = f'0 School College. Check spell<{school}> is right or create school first'
        evt_logger.error(message)
        raise ValueError(message)

    cols = ['学院', '专业', '代码', '专业简称']
    rdata = pd.read_csv(filename)
    rdata.fillna('', inplace=True)

    count = 0
    for _, series in rdata.iterrows():
        college = series['学院']
        major = series['专业']
        code = series['代码']
        short_name = series['专业简称']

        info = f'{college}-{major}'
        
        try:
            college = College.objects.get(school__name=school,  name=college)
        except College.DoesNotExist:
            message = f'{college} not exist. Check spell or create first'
            evt_logger.error(message)
            continue
        
        item = Major(
                    college=college,
                    name=major,
                    short_name=short_name,
                    code=code,
                    active=True
        )
        
        try:
            item.save()
        except Exception as e:
            evt_logger.error(f'create_major: {info} {e}')            
            continue
        else:
            evt_logger.info(f'insert_major ({count}): {info}')

        count += 1

    print(f'Total insert {count} majors.')
    
def batch_create_student(filename, school):
    college_set = College.objects.filter(school__name=school)
    if college_set is EmptyQuerySet:
        message = f'0 School College. Check spell<{school}> is right or create school first'
        evt_logger.error(message)
        raise ValueError(message)
    
    cols = ['学号', '姓名', '学院', '专业', '班级', '专业简称', 'start_year']
    rdata = pd.read_csv(filename)
    rdata.fillna('', inplace=True)
    password = make_password('123456')
    count = 0
    for _, series in rdata.iterrows():
        student_id = series['学号']
        student_name = series['姓名']
        college = series['学院']
        major = series['专业']
        student_class = series['班级']
        short_name = series['专业简称']
        start_year = series['start_year']
        
        info = f'{student_id}-{student_name}'

        if student_name == "":
            message = f'{info}: {college} Empty Name.'
            evt_logger.error(message)
            continue

        if len(student_id) != 12:
            message = f'{info}: {student_id} illegal.'
            evt_logger.error(message)
            continue

        try:
            college_obj = College.objects.get(school__name=school, name=college)
        except College.DoesNotExist:
            message = f'{info}: {college} not exist.'
            evt_logger.error(message)
            continue

        try:
            major_obj = Major.objects.get(college=college_obj, name=major)
        except Major.DoesNotExist:
            message = f'{info}: {major} not exist.'
            evt_logger.error(message)
            continue

        try:
            class_item = StudentClass.objects.get(short_name=short_name + " " + student_class,)
        except StudentClass.DoesNotExist:
            class_item = StudentClass(
                    major=major_obj,
                    name=student_class,
                    short_name=short_name + " " + student_class,
                    start_year=start_year
            )

            try:
                class_item.save()
            except Exception as e:
                message = f'{major_obj.name}-{student_class}'
                evt_logger.error(f'create_class: {message} {e}')            
                continue
        
        Student_item = Student(
                    student_id=student_id,
                    student_name=student_name,
                    password=password,
                    gender=0,
                    college=college,
                    major=major,
                    student_class=class_item
        )

        try:
            Student_item.save()
        except Exception as e:
            evt_logger.error(f'create_student: {info} {e}')            
            continue
        else:
            evt_logger.info(f'insert_student ({count}): {info}')

        count += 1

    print(f'Total insert {count} student.')
